<template>
	<view class="emain animated fadeIn faster" mode="aspectFill"  :style="{ 'background-image': $store.state.user.background? `linear-gradient(rgba(255, 255, 255, -2.4), rgba(255, 255, 255, 0.6)),url(${$store.state.user.background})` : `url('https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203377.png')` }" >
		<view class="position-fixed w-100 z-index-100 pb-1 bg-fff" :style="{'paddingTop':$store.state.statusBarHeight+'px','background':'rgba(255,255,255,'+titlebgcolor+')'}">
			<view class="d-flex d-flex-middle d-flex-between" :style="{'height': $store.state.titleBarHeight + 'px'}">
				<view class="pl-2 colorfff" @click="goBack"><text class="iconfont icon-31fanhui1 font30"></text></view>
				<view class="color000 font-bold" :style="{'opacity': titleOp}">{{$store.state.user.nickname}}</view>
			</view>
		</view>
		<view class="position-relative bg-f8" style="width: 100%; min-height: 65vh; top: calc(35vh - 150rpx);">
			<view class="bg-fff position-relative rounded30 d-flex d-flex-column d-flex-middle" style="top: -100rpx; width: 710rpx; height: 230rpx; margin: 0 auto;">
				<image class="position-absolute rounded" :src="$store.state.user.avatar" mode="aspectFill" style="transform: translateY(-50%); width: 145rpx; height: 145rpx; border: 1px solid #fff;"></image>
				<view v-show="ShowDynamic&&ShowAvatarFrams" class="position-absolute wh210" style="top: 0; left: 50%; transform: translate(-50%, -50%);">
					<l-svga ref="svga"></l-svga>
				</view>
				<view v-show="!ShowDynamic&&ShowAvatarFrams" class="position-absolute wh210" style="top: 0; left: 50%; transform: translate(-50%, -50%);">
					<image :src="iconFile" class="wh210"></image>
				</view>
				<view class="position-absolute bottom-0" style="font-size: 42rpx;">
					<view class="font-bold color000 text-center mb-1">{{$store.state.user.nickname}}</view>
					<view class="font24 mb-2" style="color: #adadad;">请选择您喜欢的头像框吧~</view>
				</view>
			</view>
			<view class="AvatarBox d-flex d-flex-wrap">
				<view v-for="(i, dex) in AvatarFrameList" :key="i.id" class="d-flex d-flex-column">
					<div :class="['AvatarItem','d-flex-btn','rounded30', selectIdx === dex? 'select' : '', (dex+1)%3===0? '' : 'mr-4']" @click="selectAva(dex)">
						<div class="avatar position-relative rounded">
							<image :src="i.icon" class="w-100 h-100"></image>
							<view v-if="i.svga && isApp!==null && isApp" class="position-absolute font22 rounded20 linerbg colorfff text-center" style="width: 65rpx; height: 28rpx; line-height: 28rpx; top: -12rpx; left: -12rpx;">动态</view>
						</div>
					</div>
					<view class="mt-1 mb-3 text-center font28">{{i.name}}</view>
				</view>
			</view>
		</view>
		
		<view v-if="selectIdx !== null" class="position-fixed d-flex-btn bg-fff bottom-0 left-0 right-0" style="height: 150rpx;">
			<view v-if="own" @click="confirm" class="font32 d-flex-btn linerbg rounded50 colorfff font-bold" style="height: 90rpx; width: 80%;">{{TopText}}</view>
			<view v-else @click="purchase" class="font32 d-flex-btn linerbg rounded50 colorfff font-bold" style="height: 90rpx; width: 80%;">立即以{{price}}元购买</view>
		</view>
		
		<uni-popup type="bottom" ref="CouponPopup" background-color="#fff" border-radius="16px 16px 0 0 " style="z-index: 10;">
			<view class="popup-content" style="height: 50vh;">
				<view class="font32 text-center mt-3 mb-5">您有以下优惠券可以使用</view>
				<view v-for="(i, index) in couponList" :key="index" class="d-flex" style="height: 145rpx; width: 90%; margin: 0 auto 30rpx;">
				  <view class="Cover rounded10" style="width: 105rpx; height: 100%;">
				    <view class="d-flex d-flex-bottom d-flex-center colorfff" style="margin-top: 15rpx;">
				      <view style="margin-bottom: 5rpx;">￥</view>
				      <view class="font-bold" style="font-size: 40rpx;">{{ i.amount }}</view>
				    </view>
				    <view class="font20 colorfff text-center" style="margin: 15rpx 2rpx;">满{{ i.limitUseAmount == 0 ? i.amount : i.limitUseAmount }}元可用</view>
				  </view>
				  <view class="Coupon_item d-flex-middle d-flex bg-fff rounded10" style="flex: 1; padding: 10rpx;">
				    <view class="d-flex d-flex-column ml-3" style="flex: 1;">
				      <view class="font24">{{ i.name }} </view>
				      <view class="font24 mt-1" style=" flex: 1;color: #b5b5b5;">有效期:{{ i.assetsExpireTime }}到期</view>
				    </view>
				    <view class="btn1 colorfff mr-3 px-2 rounded10 font20" @click="touse(i.assetsId, index)">{{UseCouponIdx!==null&&UseCouponIdx===index? '使用中' : '选择'}}</view>
				  </view>
				</view>
			</view>
			<view class="btn ml-2 colorfff" style="width: 75%; background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);" @click="unuse">不使用优惠券</view>
		</uni-popup>
		
		<uni-popup ref="purchasePopup" background-color="#fff" border-radius="10px 10px 0 0" style="z-index: 999999; position: relative;">
			<radio-group class="PayOptions d-flex-between pt-2" v-for="(item, index) in PayList" :key="item.id" @change="ChangePayOpt(index)">
			  <label class="d-flex d-flex-middle d-flex-between">
			    <view class="icon">
			      <image :src="item.icon"></image>
			    </view>
			    <view class="option mr-1" style="margin-bottom: 4rpx;">{{item.name}}</view>
			    <view v-if="item.desc" class="font22 px-3 rounded10" style="color: #FF9645; background: #f9e7c9; margin-bottom: 2px;">{{item.desc}}</view>
			  </label>
			  <radio :value="index" :checked="item.checked" style="transform:scale(0.6);"></radio>
			</radio-group>
			<view class="btn ml-2 colorfff linerbg" style="width: 75%;" @click="CreateOrder">立即以{{price}}元抢购</view>
		</uni-popup>
	</view>
</template>

<script>
	import { manner } from '../../util/manner';
	import { otherApi } from '../../http/other';
	import { PayApi } from '../../http/PayApi';
	import store from '@/store/index.js';
	export default {
		data() {
			return {
				titlebgcolor: 0,
				titleOp: 0,
				svgaFile: '', // 动态头像框地址
				iconFile: '', // 静态头像框地址
				UseAvaFramsIdx: null, // 使用的头像框下标
				assetsId: null,
				selectIdx: null, // 选择的头像框下标
				TopText: '立即使用',
				ShowDynamic: false, // 是否展示动态头像框
				ShowAvatarFrams: false, //是否展示头像框
				own: null, // 是否拥有
				AvatarFrameList: [], // 头像框列表
				couponList: [], // 优惠券列表
				price: null, // 支付的价格
				isApp: null, // App为True，小程序为False
				device: null, // Android为1，Ios为2
				isUseCoupon: false, // 是否使用了优惠券
				UseCouponIdx: null, // 使用的优惠券下标
				payMethod: 3, // 2-微信，3-支付宝
				payType: 2, // -2微信支付  -2支付宝支付
				orderStr: null, //支付宝支付字符串
				WxpayParams: {}, // 微信支付需要的参数
				PayList: [
					{
						id: 0,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241115141319.png',
						name: '支付宝',
						desc: '推荐',
						value: 'Alipay',
						checked: true
					},
					{
						id: 1,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/Pay-Wechat.png',
						name: '微信',
						desc: '',
						value: 'Wechat',
						checked: false
					},
					{
						id: 2,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%20554.png',
						name: '嗒币',
						desc: '',
						value: 'Dabi',
						checked: false
					}
				]
			}
		},
		onLoad() {
			// #ifdef APP
				this.isApp = true
			// #endif
			//#ifdef MP-WEIXIN
				this.isApp = false
			// #endif
			
			uni.getSystemInfo({
				success: (res) => {
					this.device = res.osName==='android'? 1 : 2
				}
			});
			
			this.getAvatarFrams()
		},
		methods: {
			goBack(){
				manner.goBack()
			},
			// 停止播放svga动画
			StopPlaying() {
				this.$refs.svga.render(async (parser, player) => {
					let svgaFile = this.svgaFile
				    const videoItem = await parser.load(svgaFile);
				    player.stopAnimation(true)
				})
			},
			// 开始播放svga动画
			StarPlaying() {
				this.$refs.svga.render(async (parser, player) => {
					let svgaFile = this.svgaFile
				    const videoItem = await parser.load(svgaFile);
				    await player.setVideoItem(videoItem);
				    player.loops = 0
				    player.setContentMode(() => {
						contentMode: 'AspectFit' 
					})
				    player.startAnimation()
				})
			},
			// 选择头像框
			selectAva(dex) {
				if(dex === this.selectIdx) return
				
				this.selectIdx = dex
				
				if(this.UseAvaFramsIdx===this.selectIdx) {
					this.TopText = '使用中'
				} else {
					this.TopText = '立即使用'
				}
				
				// 如果动态头像框还在展示就先停下来
				if(this.ShowDynamic) {
					this.StopPlaying()
				}
				
				// 头像框没有展示的话就展示出来
				if(!this.ShowAvatarFrams) {
					this.ShowAvatarFrams = true
				}
				
				this.own = this.AvatarFrameList[dex].count? true : false
				this.assetsId = this.AvatarFrameList[dex].assetsId
				this.iconFile = this.AvatarFrameList[dex].icon
				this.price = this.device===1 ? this.AvatarFrameList[dex].androidPrice : this.AvatarFrameList[dex].iosPrice
				
				if(this.AvatarFrameList[dex].svga && this.isApp) {
					this.ShowDynamic = true
					this.svgaFile = this.AvatarFrameList[dex].svga
					setTimeout(() => {
						this.StarPlaying()
					},200)
				} else {
					this.ShowDynamic = false
				}
			},
			// 使用头像框
			confirm() {
				if(this.TopText == '立即使用') {
					this.SetAvatarFrams()
				}
			},
			// 立即购买
			purchase() {
				this.getCoupon()
			},
			// 获取头像框数据
			async getAvatarFrams(type) {
				let params = {
					type: 1
				}
				let res = await otherApi.getAvatarFrams(params);
				this.AvatarFrameList = res.records
				
				if(type && type==2) return
				
				// 如果用户设置了头像框则先选中该头像框
				let AvatarFramsId = null
				let AvatarFramsName = null
				if(this.$store.state.user.dressedVoMap['1']) {
					AvatarFramsId = this.$store.state.user.dressedVoMap[1].id
					AvatarFramsName = this.$store.state.user.dressedVoMap[1].name
				}
				this.AvatarFrameList.forEach((item, dex) => {
					if(item.id === AvatarFramsId && item.name ===AvatarFramsName) {
						this.UseAvaFramsIdx = dex
						this.selectAva(dex)
					}
				})
			},
			// 设置装扮
			async SetAvatarFrams() {
				let params = {
					assetsId: this.assetsId
				}
				let res = await otherApi.SetAvatarFrams(params);
				this.TopText = '使用中'
				uni.showToast({
					icon: 'none',
					title: '设置成功',
					duration: 1500
				})
			},
			// 查询可用优惠券
			async getCoupon() {
				const params = {
					resourceType: 14,
					amount: this.price
			    }
				this.couponList = []
			    const res = await PayApi.getCoupon(params);
			    this.couponList = res;
				if(this.couponList.length) {
					this.$refs.CouponPopup.open('bottom')
				} else {
					this.$refs.purchasePopup.open('bottom')
				}
			},
			// 使用优惠券
			touse(assetsId, dex) {
				if(this.isUseCoupon && this.UseCouponIdx===dex) {
					uni.showToast({
						icon: 'none',
						title: '此优惠券正在使用中',
						position: 'bottom',
						duration: 1500
					})
					return
				}
				this.$refs.CouponPopup.close()
				this.couponList.forEach((i, dex) => {
					if(i.assetsId === assetsId) {
						setTimeout(() => {
							this.price -= i.amount
							this.isUseCoupon = true
							this.UseCouponIdx = dex
							this.$refs.purchasePopup.open('bottom')
						}, 800)
					}
				})
			},
			// 不使用优惠券
			unuse() {
				this.$refs.CouponPopup.close()
				this.price = this.device===1 ? this.AvatarFrameList[this.selectIdx].androidPrice : this.AvatarFrameList[this.selectIdx].iosPrice
				this.isUseCoupon = false
				this.UseCouponIdx = null
				setTimeout(() => {
					this.$refs.purchasePopup.open('bottom')
				}, 600)
			},
			// 切换支付选择项
			ChangePayOpt(dex) {
				this.PayList[dex].checked = true
				this.payMethod = this.PayList[dex].id===0? 3 : this.PayList[dex].id===1? 2 : 1
				this.payType = this.PayList[dex].id===0 || this.PayList[dex].id===1 ? 2 : this.PayList[dex].id===2? 1 : null
				this.PayList.forEach((i, index) => {
					if(dex !== index) {
						this.PayList[index].checked = false
					}
				})
			},
			// 点击支付按钮创建订单
			async CreateOrder() {
				let params = {
					sourceType: this.device,
					id: this.AvatarFrameList[this.selectIdx].id
				}
				if(this.isUseCoupon) {
					params.couponAssetsId = this.couponList[this.UseCouponIdx].assetsId
				}
				let res = await PayApi.CreateAvatarFramsOrder(params)
				console.log(res.orderNo);
				this.Pay(res.orderNo)
			},
			// 开始支付
			async Pay(orderNo) {
				let params = {
					orderNo: orderNo,
					payMethod: this.payMethod,
					payType: this.payType
				}
				const res = await PayApi.Pay(params)
				
				// 支付宝支付
				if(this.payMethod === 3) {
					this.orderStr = res.params.orderStr
					this.payByAlipay()
					return
				}
				// 微信支付
				if(this.payMethod === 2) {
					this.WxpayParams = {}
					this.WxpayParams = res.params
					this.payByWxpay();
					return
				}
				// 嗒币支付
				if(this.payMethod === 1) {
					console.log(res.paySuccess);
					uni.showToast({
						title: '支付成功',
						icon: 'none',
						position: 'bottom',
						duration: 1000 // 显示持续时间
					});
					uni.showLoading({
						icon: 'none',
						title: '加载中...'
					})
					setTimeout(() => {
						this.getAvatarFrams(2)
						setTimeout(() => {
							console.log(this.AvatarFrameList[this.selectIdx]);
							this.assetsId = this.AvatarFrameList[this.selectIdx].assetsId
							this.own = true
							uni.hideLoading()
						}, 1000)
					}, 1000)
					this.$refs.purchasePopup.close()
				}
			},
			// 微信支付
			payByWxpay() {
				uni.requestPayment({
					"provider": "wxpay", // 微信支付
					"orderInfo": {
					"appid": this.WxpayParams.appid,
					"timestamp":this.WxpayParams.timestamp,
					"noncestr": this.WxpayParams.noncestr,
					"package": "Sign=WXPay", 
					"partnerid": this.WxpayParams.partnerId,
					"prepayid": this.WxpayParams.prepayId, 
					"sign": this.WxpayParams.sign
					},
					success: (res) => {
						console.log('支付成功', res);
						// 支付成功的处理逻辑
						uni.showToast({
							title: '支付成功',
							icon: 'none',
							position: 'bottom',
							duration: 1500
						});
						uni.showLoading({
							icon: 'none',
							title: '加载中...'
						})
						setTimeout(() => {
							this.getAvatarFrams(2)
							setTimeout(() => {
								console.log(this.AvatarFrameList[this.selectIdx]);
								this.assetsId = this.AvatarFrameList[this.selectIdx].assetsId
								this.own = true
								uni.hideLoading()
							}, 1000)
						}, 1000)
						this.$refs.purchasePopup.close()
					},
					fail: (err) => {
						console.log('支付失败，错误信息：', err);
						if (err.errCode === 'xxx') { 
							// 可以根据不同的 errCode 进行不同的处理，这里的 xxx 是具体的错误码，例如用户取消支付的错误码
							console.log('用户取消支付');
						} else if (err.errCode === 'yyy') { 
							// 另一种错误码 yyy 的处理
							console.log('签名错误，请联系客服');
						} else {
							console.log('其他支付错误，请重试或联系客服');
						}
						uni.showToast({
							title: '支付失败',
							icon: 'none',
							position: 'bottom',
							duration: 2000
						});
						this.$refs.purchasePopup.close()
					}
				});
			},
			// 支付宝支付
			payByAlipay() {
				const orderStr = this.orderStr;
				if (!orderStr) {
					console.error('订单字符串为空，无法进行支付');
					return;
				}
				// 调用 uni.requestPayment 方法
				uni.requestPayment({
					provider: 'alipay', // 指定支付提供商为支付宝
					orderInfo: orderStr, // 订单信息
					success: (res) => {
						uni.showToast({
							title: '支付成功',
							icon: 'none',
							position: 'bottom',
							duration: 1000 // 显示持续时间
						});
						uni.showLoading({
							icon: 'none',
							title: '加载中...'
						})
						setTimeout(() => {
							this.getAvatarFrams(2)
							setTimeout(() => {
								console.log(this.AvatarFrameList[this.selectIdx]);
								this.assetsId = this.AvatarFrameList[this.selectIdx].assetsId
								this.own = true
								uni.hideLoading()
							}, 1000)
						}, 1000)
						this.$refs.purchasePopup.close()
					},
					fail: (err) => {
						console.error('支付失败:', err);
					    uni.showToast({
						   title: '支付失败',
						   icon: 'none',
						   position: 'bottom',
						   duration: 1000 // 显示持续时间
						});
						this.$refs.purchasePopup.close()
					}
				});
			}
		}
	}
</script>

<style scoped>
/* 隐藏滚动条 */
::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
}
.emain{
	background-repeat: no-repeat;
	background-size: cover;
	background-position: 0 100%;
	min-height: 55vh;
	max-height: 55vh;
	position: relative;
}
.AvatarBox {
	width: 710rpx;
	margin: 0 auto;
}
.AvatarItem {
	width: 210rpx;
	height: 210rpx;
	background: #fff;
	box-sizing: border-box;
}
.AvatarItem .avatar {
	width: 165rpx;
	height: 165rpx;
	background: radial-gradient(circle at center, #f7f7f7, #f8f8f8, #f9f9f9, #fafafa, #fbfbfb, #fcfcfc, #fbfbfb, #fafafa);
}
.select {
	border: 1px solid #e0a2a4;
}
.wh210 {
	width: 210rpx;
	height: 210rpx;
}
.Cover {
	border-right: 1px dashed #f5f5f5;
	background-image: linear-gradient(135deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
}
.Coupon_item {
	flex: 1;
	box-shadow: 3px 3px 3px rgba(0, 0, 0, .1);
}
.btn {
	margin: 30rpx auto 20rpx;
	text-align: center;
	font-size: 30rpx;
	height: 87rpx;
	line-height: 87rpx;
	border-radius: 50rpx;
}
.btn1 {
	height: 40rpx !important;
	line-height: 40rpx !important;
	background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
}
.PayOptions {
	width: 680rpx;
	margin: 0 auto;
	display: flex;
	align-items: center;
	margin-top: 30rpx;
}
.PayOptions .option {
	color: #231815;
	font-size: 28rpx;
}
.PayOptions .icon {
	margin-right: 26rpx;
}
.PayOptions .icon image {
	width: 64rpx;
	height: 64rpx;
}
</style>